import { JSEncrypt } from 'jsencrypt'
import SM2 from './sm2/index'
import SM4 from './sm4/index'
import CryptoJS from 'crypto-js'

const PUBLIC_KEY = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpzfG8Q+Ro/ZALQtXnXHD+1YOEGcIeCThRRfs8iCvqAjjT+MccbVxsrsNcvyMOvb/aXZ4pPPv0RDcjYfuSnXRlHctIEERotS+EOdlNTqSBZQUS86H0+hDMnXa8FgkUR2g950gcKjjmV3GrGWUZYMQCz/ik1BnBt72Ft8v6IFEOtQIDAQAB`

const SM2_PUBLIC_KEY = '04F6D326509BA8DA09AA34CD85AEF79DBA45FD17E675541B15EF5EC9B8F4AB18BCA13A2F04C6BC1607CA72CC296A9ACF7BF26891C32B210B947CA88F3B92801E8F'

const SM2_PRIVATE_KEY = '9ED45E25826B67E8ACCD63D3E1605179CF417E2ADB391361CDBF367EC1687ECE'

function getRandomKey () {
  return (Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2)).substr(0, 16)
}

function encryptParams (params, key) {
  let encryptedKey = RSAencrypt(key, PUBLIC_KEY)
  if (!params) {
    return JSON.stringify({ key: encryptedKey })
  }
  let encryptData = params
  if (Object.prototype.toString.call(params) === '[object Object]' || Object.prototype.toString.call(params) === '[object Array]') {
    encryptData = AESencrypt(JSON.stringify(params), key)
  }
  return { key: encryptedKey, data: encryptData }
}

function RSAencrypt (data, key = PUBLIC_KEY) {
  if (!data) {
    return data
  }
  var jsEncrypt = new JSEncrypt()
  jsEncrypt.setPublicKey(key)
  let result = jsEncrypt.encrypt(data)
  return result
}

function AESencrypt (word, key) {
  if (!word) {
    return word
  }
  var keys = CryptoJS.enc.Utf8.parse(key)
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, keys, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

function AESdecrypt (data, key) {
  if (!data) {
    return data
  }
  key = CryptoJS.enc.Utf8.parse(key)
  var decrypt = CryptoJS.AES.decrypt(data, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

function SM2Encrypt (msg, key = SM2_PUBLIC_KEY) {
  if (!msg) {
    return msg
  }
  return SM2.doEncrypt(msg, key)
}

function SM2Decrypt (msg, key = SM2_PRIVATE_KEY) {
  if (!msg) {
    return msg
  }
  return SM2.doDecrypt(msg, key)
}

function SM4Encrypt (msg, key) {
  if (!msg) {
    return msg
  }
  return SM4.encrypt(JSON.stringify(msg), key)
}

function SM4Dncrypt (msg, key) {
  if (!msg) {
    return msg
  }
  return SM4.decrypt(msg, key)
}

export default {
  PUBLIC_KEY,
  getRandomKey,
  encryptParams,
  RSAencrypt,
  AESencrypt,
  AESdecrypt,
  SM2Encrypt,
  SM2Decrypt,
  SM4Encrypt,
  SM4Dncrypt
}
